//
//  KeyValueStore.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/11/17.
//

import Foundation
import CoreData

let kKeyValue = "KeyValue"

class KeyValueStore {
    
    static func set(key: String, value: String?) {
        guard let value = value else { return }
        
        let managedContext = CoreDataStack.shared.managedContext
        if let objc = find(key) { // 有，改
            objc.value = value
        } else { // 无，加
            let objc = NSEntityDescription.insertNewObject(forEntityName: kKeyValue, into: managedContext) as! KeyValue
            objc.key = key
            objc.value = value
        }
        
        do {
            try managedContext.save()
            print("操作成功")
        } catch {
            print("操作失败：\(error)")
        }
    }
    
    static func get(_ key: String) -> String? {
        return find(key)?.value
    }
    
    static func find(_ key: String) -> KeyValue? {
        let managedContext = CoreDataStack.shared.managedContext
        let fetchRequest = NSFetchRequest<KeyValue>(entityName: kKeyValue)
        let predicate = NSPredicate(format: "key == %@", key) // 设置查询条件
        fetchRequest.predicate = predicate

        do {
            let fetchedObjects = try managedContext.fetch(fetchRequest)
            return fetchedObjects.first
        } catch {
            print("错误：\(error)")
        }
        
        return nil
    }
}
